<?php
class RelatedContent extends BlockInstance {
	public $CI;
	
	function RelatedContent()
	{
		$this->CI =& get_instance();
	}
	
	function __call($m, $a)
	{
		$content = $a[1];
		$inst	 = $a[0]['data'];
		
		// find all users who have engaged this
		$ids   = array();
		$query = $this->CI->db->query('select user_id from engagements where content_id = ?', array($content->id));
		foreach ($query->result() as $r)
			$ids[] = $r->user_id;
		
		if (count($ids))
		{
			$rel_id_query = $this->CI->db->query('select content_id from engagements
													  inner join contents on contents.id = content_id
                                                      where engagements.user_id in (?)
														and engagements.content_id <> ?
                                                        and engagements.content_id in
															(select id from contents where bricabox_id = ?)
                                                      limit 10',
														array(join(',', $ids), $content->id, $content->bricabox_id));
			if ($rel_id_query->num_rows())
			{
				$ids_in = array();
				foreach ($rel_id_query->result() as $r)
					$ids_in[] = $r->content_id;
					
				if (count($ids_in))
				{
					$query = $this->CI->db->query('select * from contents where bricabox_id = ? and id in ('.join(',', $ids_in).')', array($content->bricabox_id));
					if ($query->num_rows())
					{
						$data['related'] = $query;
						$this->CI->load->view('blocks/related/content', $data);
					}
					else
					{
						echo 'No related entries found.';
					}
				}
			}
		}
	}
}
?>